(() => {
    // DOM元素
    const elements = {
        notifyBtn: document.getElementById('notifyBtn'),
        messageInput: document.getElementById('messageInput'),
        callSlider: document.getElementById('callSlider'),
        callHandle: document.getElementById('callHandle'),
        callProgress: document.getElementById('callProgress'),
        historyToggle: document.getElementById('historyToggle'),
        historyList: document.getElementById('historyList'),
        historyCount: document.getElementById('historyCount'),
        toastContainer: document.getElementById('toastContainer'),
        themeBtns: document.querySelectorAll('[data-theme]'),
        adminEntry: document.getElementById('adminEntry'),
        passwordModal: document.getElementById('passwordModal'),
        passwordInput: document.getElementById('passwordInput'),
        passwordSubmit: document.getElementById('passwordSubmit'),
        passwordCancel: document.getElementById('passwordCancel')
    };

    // 状态管理
    const state = {
        lastNotifyTime: 0,
        isDragging: false,
        startX: 0,
        currentX: 0,
        maxProgress: 0,
        notificationHistory: [],
        isNotifying: false // 添加发送状态标记
    };

    // 触觉反馈
    const hapticFeedback = {
        light: () => navigator.vibrate?.(10),
        medium: () => navigator.vibrate?.(30),
        heavy: () => navigator.vibrate?.([50, 50, 50]),
        success: () => navigator.vibrate?.([50, 30, 50, 30, 50])
    };

    // 主题切换
    function setTheme(theme) {
        document.body.className = theme;
        elements.themeBtns.forEach(btn => {
            btn.classList.toggle('active', btn.dataset.theme === theme);
        });
        localStorage.setItem('theme', theme);
        hapticFeedback.light();
    }

    // Toast提示
    async function showToast(message, type = 'info') {
        const toast = elements.toastContainer;
        const text = toast.querySelector('.toast-message');
        text.textContent = message;
        toast.classList.add('show');

        if (type !== 'loading') {
            setTimeout(() => {
                toast.classList.remove('show');
            }, 2000);
        }
    }

    // 加载通知历史
    async function loadNotifications() {
        try {
            const response = await fetch('api.php?action=getNotifications');
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            state.notificationHistory = data.data;
            updateHistoryDisplay();
        } catch (error) {
            console.error('加载历史记录失败:', error);
            await showToast('加载历史记录失败', 'error');
        }
    }

    // 更新历史记录显示
    function updateHistoryDisplay() {
        elements.historyCount.textContent = `${state.notificationHistory.length}条记录`;
        elements.historyList.innerHTML = state.notificationHistory.length === 0 
            ? '<div class="history-item">暂无通知记录</div>'
            : state.notificationHistory.map(notification => `
                <div class="history-item">
                    <div class="history-message">${notification.message}</div>
                    <div class="history-time">
                        ${new Date(notification.timestamp).toLocaleString()}
                    </div>
                </div>
            `).join('');
    }

    // 发送通知
    async function notifyOwner() {
        // 防止重复发送
        if (state.isNotifying) return;

        const config = window.config;
        const now = Date.now();
        if (now - state.lastNotifyTime < config.notification.cooldown) {
            const remaining = Math.ceil((config.notification.cooldown - (now - state.lastNotifyTime)) / 1000);
            await showToast(
                `请等待 ${Math.floor(remaining / 60)}分${remaining % 60}秒后再次通知`,
                'error'
            );
            return;
        }

        const message = elements.messageInput.value.trim() || config.notification.defaultMessage;
        
        try {
            state.isNotifying = true; // 设置发送状态
            hapticFeedback.medium();
            await showToast('正在通知车主...', 'loading');
            
            const response = await fetch('api.php?action=addNotification', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message })
            });

            if (!response.ok) throw new Error('Network response was not ok');

            const data = await response.json();
            if (!data.success) throw new Error(data.error);

            hapticFeedback.success();
            await showToast('已成功通知车主，请稍候！', 'success');
            state.lastNotifyTime = now;
            elements.messageInput.value = '';
            await loadNotifications();
        } catch (error) {
            console.error('通知发送失败:', error);
            hapticFeedback.heavy();
            await showToast('发送失败，请检查网络后重试', 'error');
        } finally {
            state.isNotifying = false; // 重置发送状态
        }
    }

    // 更新滑块位置
    function updateSlider(clientX) {
        const rect = elements.callSlider.getBoundingClientRect();
        const maxX = rect.width - elements.callHandle.offsetWidth;
        state.currentX = Math.max(0, Math.min(maxX, clientX - rect.left - elements.callHandle.offsetWidth / 2));
        
        const progress = (state.currentX / maxX) * 100;
        
        if (progress > state.maxProgress) {
            state.maxProgress = progress;
            if (progress > 25 && progress < 90) {
                hapticFeedback.light();
            }
        }
        
        elements.callHandle.style.transform = `translateX(${state.currentX}px)`;
        elements.callProgress.style.width = `${progress}%`;

        if (progress > 90) {
            const config = window.config;
            hapticFeedback.success();
            window.location.href = `tel:${config.phone}`;
            setTimeout(resetSlider, 300);
        }
    }

    // 重置滑块
    function resetSlider() {
        elements.callHandle.style.transform = 'translateX(0)';
        elements.callProgress.style.width = '0';
        state.currentX = 0;
        state.isDragging = false;
        state.maxProgress = 0;
        hapticFeedback.medium();
    }

    // 管理入口
    async function handleAdminEntry() {
        elements.passwordModal.classList.add('show');
        elements.passwordInput.focus();
    }

    // 密码验证
    async function handlePasswordSubmit() {
        const password = elements.passwordInput.value;
        if (!password) {
            await showToast('请输入密码', 'error');
            return;
        }

        try {
            const response = await fetch('api.php?action=verifyPassword', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ password })
            });

            const data = await response.json();
            if (data.success) {
                window.location.href = 'admin.html';
            } else {
                await showToast('密码错误', 'error');
            }
        } catch (error) {
            await showToast('验证失败，请重试', 'error');
        }

        elements.passwordInput.value = '';
        elements.passwordModal.classList.remove('show');
    }

    // 初始化
    function init() {
        // 初始化主题
        const savedTheme = localStorage.getItem('theme') || 'light';
        setTheme(savedTheme);

        // 加载通知历史
        loadNotifications();

        // 主题切换
        elements.themeBtns.forEach(btn => {
            btn.addEventListener('click', () => setTheme(btn.dataset.theme));
        });

        // 历史记录切换
        elements.historyToggle.addEventListener('click', () => {
            elements.historyList.classList.toggle('show');
            hapticFeedback.light();
        });

        // 通知按钮
        elements.notifyBtn.addEventListener('click', notifyOwner);

        // 管理入口
        elements.adminEntry.addEventListener('click', handleAdminEntry);
        elements.passwordSubmit.addEventListener('click', handlePasswordSubmit);
        elements.passwordCancel.addEventListener('click', () => {
            elements.passwordModal.classList.remove('show');
            elements.passwordInput.value = '';
        });

        // 密码输入框事件
        elements.passwordInput.addEventListener('keyup', (e) => {
            if (e.key === 'Enter') handlePasswordSubmit();
            if (e.key === 'Escape') elements.passwordModal.classList.remove('show');
        });

        // 滑块事件
        elements.callSlider.addEventListener('touchstart', (e) => {
            state.isDragging = true;
            state.startX = e.touches[0].clientX;
            elements.callHandle.style.transition = 'none';
            elements.callProgress.style.transition = 'none';
            hapticFeedback.light();
        }, { passive: true });

        elements.callSlider.addEventListener('touchmove', (e) => {
            if (!state.isDragging) return;
            e.preventDefault();
            updateSlider(e.touches[0].clientX);
        }, { passive: false });

        elements.callSlider.addEventListener('mousedown', (e) => {
            state.isDragging = true;
            state.startX = e.clientX;
            elements.callHandle.style.transition = 'none';
            elements.callProgress.style.transition = 'none';
        });

        document.addEventListener('mousemove', (e) => {
            if (!state.isDragging) return;
            e.preventDefault();
            updateSlider(e.clientX);
        }, { passive: false });

        // 防止页面滚动
        document.addEventListener('touchmove', (e) => {
            if (state.isDragging) e.preventDefault();
        }, { passive: false });

        ['mouseup', 'mouseleave', 'touchend', 'touchcancel'].forEach(event => {
            document.addEventListener(event, () => {
                if (!state.isDragging) return;
                state.isDragging = false;
                elements.callHandle.style.transition = 'transform 0.3s';
                elements.callProgress.style.transition = 'width 0.3s';
                resetSlider();
            }, { passive: true });
        });

        // 定时刷新历史记录
        setInterval(loadNotifications, 60000);
    }

    init();
})();